﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infov1.Models;
using Infov1.Commands;
using SqlSugar;
using System.Windows.Input;
using System.Windows;
using HandyControl.Controls;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;

namespace Infov1.ViewModels
{
   
        public class CustomerAreaViewModel : ViewModelBase
        {
       
            // 数据库访问对象
            private readonly ISqlSugarClient _db;
            // 区域列表集合
            private ObservableCollection<CustomerAreaModel> _areaList;
            //添加一个编辑标志
            private bool _isEditing;
            // 添加选中项
            private CustomerAreaModel _selectedArea;
            // 是否为新增模式
            private bool _isNewMode;
            //编辑的时候保存时，记录下原来的编码
            private string _oldAreaCode;

        
        /// <summary>
        /// 构造函数：初始化数据库连接并加载数据
        /// </summary>
        public CustomerAreaViewModel()
            {
            
            // 获取数据库连接
            _db = DbContext.GetConnection();
                // 初始化查询命令
                LoadAreaCommand = new RelayCommand(LoadAreas);
                // 初始化添加命令
                AddNewCommand = new RelayCommand(AddNew);
                // 初始化保存命令
                SaveCommand = new RelayCommand(Save);
                //初始化 编辑命令
                StartEditCommand = new RelayCommand(StartEdit);
                //初始化删除命令
                DeleteCommand = new RelayCommand(Delete);
                //初始化刷新命令
                RefreshCommand = new RelayCommand(Refresh);
            // 加载数据
            LoadAreas();
            }
            /// <summary>
            /// 加载数据命令
            /// </summary>
            public ICommand LoadAreaCommand { get; }
            public ICommand AddNewCommand { get; }
            public ICommand SaveCommand { get; }
            public ICommand StartEditCommand { get; }
            public ICommand DeleteCommand { get; }
            public ICommand RefreshCommand { get; }
            
        /// <summary>
        /// 区域列表属性，用于界面绑定
        /// </summary>
        public ObservableCollection<CustomerAreaModel> AreaList
                {
                    get => _areaList;
                    set
                    {
                        _areaList = value;
                        OnPropertyChanged(nameof(AreaList));
                    }
                }
            /// <summary>
            /// 编辑状态属性
            /// </summary>
            public bool IsEditing
            {
                get => _isEditing;
                set
                {
                    _isEditing = value;
                    OnPropertyChanged(nameof(IsEditing));
                }
            }
        /// <summary>
        /// 绑定选中行选中行
        /// </summary>
        public CustomerAreaModel SelectedArea
        {
            get => _selectedArea;
            set
            {
                _selectedArea = value;
                OnPropertyChanged(nameof(SelectedArea));
            }
        }
        /// <summary>
        /// 加载区域数据的方法
        /// </summary>
        private void LoadAreas()
            {
            IsEditing = false;
            _isNewMode = false;
            if (_db == null) return;

                // 查询区域数据
                var areas = _db.Queryable<CustomerAreaModel>()
                    .ToList();
                // 更新列表
                AreaList = new ObservableCollection<CustomerAreaModel>(areas);
            

        }
        /// <summary>
        /// 新增区域的方法
        /// </summary>
        private void AddNew()
        {
            IsEditing = true;
            // 设置为新增模式
            _isNewMode = true; 
            SelectedArea = null;
            AreaList = new ObservableCollection<CustomerAreaModel>
            {
                new CustomerAreaModel()
            };
        }

        /// <summary>
        /// 保存区域的方法
        /// </summary>
        private void Save()
        {
            if (!IsEditing) return;

            var area = AreaList.FirstOrDefault();
            
            if (area == null) return;
            // 验证输入
            if (string.IsNullOrEmpty(area.AreaCode))
            {
                HandyControl.Controls.Growl.Warning("请输入有效编码,必须大于0！");
                return;
            }
            // 验证输入
            if (!int.TryParse(area.AreaCode.ToString(), out int codeValue) || codeValue <= 0)
            {
                HandyControl.Controls.Growl.Warning("请输入有效编码,必须大于0！");
                return;
            }

            if (string.IsNullOrWhiteSpace(area.AreaName))
            {
                HandyControl.Controls.Growl.Warning("区域名称不能为空！");
                return;
            }
            try
            {
                if (_isNewMode)
                {
                    // 新增模式：检查编码是否已存在
                    var exists = _db.Queryable<CustomerAreaModel>()
                        .Any(x => x.AreaCode == area.AreaCode);
                    if (exists)
                    {
                        HandyControl.Controls.Growl.Warning("区域编码已存在！");
                        return;
                    }
                    //判断 编码位数  不能超过 或小于2位
                    if (area.AreaCode.Length != 2)
                    {
                        HandyControl.Controls.Growl.Warning("区域必须为两位！");
                        return;
                    }

                    // 执行新增
                    _db.Insertable(area).ExecuteCommand();
                    HandyControl.Controls.Growl.Success("新增成功！");
                    
                }
                else
                {
                   
                    if (area.AreaCode != _oldAreaCode)
                    {
                        HandyControl.Controls.Growl.Warning("区域编码不允许修改！");
                        return;
                    }

                    // 执行更新
                    _db.Updateable(area).ExecuteCommand();
                    HandyControl.Controls.Growl.Success("更新成功！");
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error($"保存失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 开始编辑
        /// </summary>
        private void StartEdit()
        {
            if (SelectedArea == null || string.IsNullOrWhiteSpace(SelectedArea.AreaCode))
            {
                HandyControl.Controls.Growl.Warning("请选择要编辑的区域！");
                return;
            }
            //编辑时 获取旧编码  保存的时候 判断是否修改
            _oldAreaCode = SelectedArea.AreaCode;
            IsEditing = true;
            _isNewMode = false;
            // 创建编辑副本
            AreaList = new ObservableCollection<CustomerAreaModel>
            {
                new CustomerAreaModel
                {
                    AreaCode = SelectedArea.AreaCode,
                    AreaName = SelectedArea.AreaName
                }
            };
        }
        private void Delete()
        {
            if (_isNewMode || _isEditing)
            {
                HandyControl.Controls.Growl.Warning("此模式下不允许删除！");
                return;
            }
            if (SelectedArea== null)
            {
                HandyControl.Controls.Growl.Warning("请选择要删除的内容！");
                return;
            }
            // 弹出确认对话框
            MessageBoxResult result = HandyControl.Controls.MessageBox.Show(
                "确定要删除所选区域吗？",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            // 如果用户选择不删除或关闭了对话框，则返回
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            try
            {
                // 删除区域
                _db.Deleteable<CustomerAreaModel>()
                    .Where(x => x.AreaCode == SelectedArea.AreaCode)
                    .ExecuteCommand();

                // 重新加载数据
                LoadAreas();
                _isNewMode = false;
                SelectedArea = null;
                HandyControl.Controls.Growl.Success("删除成功！");
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error($"删除失败：{ex.Message}");
            }
        }
        private void Refresh()
        {
            LoadAreas();
        }
    }  
}
